package main

import (
    "fmt"
    "net/http"
    "log"
    "github.com/gorilla/mux"
)

func logging(f http.HandlerFunc) http.HandlerFunc{
   // 中间件
    return func(w http.ResponseWriter, r *http.Request) {
        log.Println(r.URL.Path)
        f(w, r)
    }
}

func foo(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "foo")
}

func bar(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "bar")
}

func books(w http.ResponseWriter, r *http.Request){
    vars:= mux.Vars(r)
    title := vars["title"]
    page := vars["page"]
    fmt.Println("inside")
    fmt.Fprintf(w, "You've requested the book: %s on page %s\n", title, page)
}

func main() {
    fmt.Println("begin")

    r := mux.NewRouter()
    // r.HandleFunc("/books/{title}/page/{page}", func(w http.ResponseWriter, r *http.Request){
    //   vars:= mux.Vars(r)
    //   title := vars["title"]
    //   page := vars["page"]
    //   fmt.Println("inside")
    //   fmt.Fprintf(w, "You've requested the book: %s on page %s\n", title, page)
    // })

    r.HandleFunc("/foo", logging(foo))
    r.HandleFunc("/bar", logging(bar))
    r.HandleFunc("/books/{title}/page/{page}", logging(books))
    
    // http.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
    //     fmt.Fprintf(w, "Hello, Welcome! you've requested: %s\n", r.URL.Path)
    // })
    // 静态文件
    // fs := http.FileServer(http.Dir("static/"))
    // http.Handle("/static", http.StripPrefix("/static", fs))
    http.ListenAndServe(":8081", r)
}